package com.sunmouse.toolkit.fragment.other;


import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.sunmouse.toollib.adapter.BasicRecyclerAdapter;
import com.sunmouse.toollib.adapter.OnChildClickListener;
import com.sunmouse.toollib.utils.FileUtils;
import com.sunmouse.toollib.utils.LogUtils;
import com.sunmouse.toollib.utils.ToastUtils;
import com.sunmouse.toollib.utils.load.LoadRequest;
import com.sunmouse.toollib.utils.load.LoadUtils;
import com.sunmouse.toolkit.R;
import com.sunmouse.toolkit.adapter.LoadAdapter;
import com.sunmouse.toolkit.bean.MediaBean;
import com.sunmouse.toolkit.fragment.BaseFragment;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class LoadFragment extends BaseFragment {


    @BindView(R.id.add_btn)
    Button addBtn;
    @BindView(R.id.m_list)
    RecyclerView mList;
    @BindView(R.id.start_btn)
    Button startBtn;
    @BindView(R.id.stop_all_btn)
    Button stopAllBtn;
    @BindView(R.id.start_all_btn)
    Button startAllBtn;
    Unbinder unbinder;

    private ArrayList<MediaBean> mData;
    private LoadAdapter mAdapter;
    private LoadUtils mLoadUtils;
    private int index;
    private boolean isLoading;
    private Timer mTimer;

    public LoadFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_load, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void init() {
        this.mData = new ArrayList<>();
        this.mAdapter = new LoadAdapter(mData, getActivity());
        this.mList.setLayoutManager(new LinearLayoutManager(getActivity()));
        this.mList.setAdapter(mAdapter);
//        this.mAdapter.setOnChildClickListener(new ChildClick());
        this.mAdapter.setOnItemClickListener(new ItemClick());
        this.addBtn.setOnClickListener(this);
        this.startBtn.setOnClickListener(this);
        this.startAllBtn.setOnClickListener(this);
        this.stopAllBtn.setOnClickListener(this);

        this.mLoadUtils = LoadUtils.init()
                .mode(LoadUtils.Mode.MULTI_TASK)
                .msgDelay(1000)
                .limitExecuteNum(3)
                .build(getActivity(),mLoadingListener);
    }


    @Override
    public void onClick(View v) {
        if (v == addBtn) {
//            String url = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2791674927,1091799816&fm=27&gp=0.jpg";
            String url = "http://www.wandoujia.com/apps/com.jgw.supercode/download?pos=detail-ndownload-com.jgw.supercode";
            String localPath = FileUtils.getStoragePath() + "/image/" + ((long) (1000000000 * Math.random())) + ".apk";
            MediaBean bean = new MediaBean();
            bean.setName(String.valueOf((long) (1000000000 * Math.random())));
            bean.setRemoteUrl(url);
            bean.setLocalPath(localPath);
            mData.add(bean);
            mAdapter.notifyDataSetChanged();
            mLoadUtils.addRequest(new LoadRequest.Builder(localPath, url).build());
            loading();
            return;
        }
        if (v == startBtn) {
            if (mLoadUtils.isStop(index)) {
                mLoadUtils.start(index);
                return;
            }
            mLoadUtils.stop(index);
            return;
        }

        if (v == startAllBtn) {
            mLoadUtils.startAll();
            return;
        }
        if (v == stopAllBtn) {
            mLoadUtils.stopAll();
        }
    }

    private void loading() {
        if (isLoading) return;
        isLoading = true;
        index = 0;
        this.mLoadUtils.enqueue();

    }

    /**
     * init timer
     */
    private void initTimer() {
        if (mTimer == null) {
            mTimer = new Timer();
            mTimer.schedule(new ProgressTask(), 0, 1000);
        }
    }

    @Override
    public void onHandleMessage(Message msg) {
        if (index >= mData.size() || index < 0) return;
        if (msg.what == 12) {
            mData.get(index).setProgress(mLoadUtils.getProgress() * 100 / mLoadUtils.getLength());
            mAdapter.notifyDataSetChanged();
        }
    }


    /**
     * load listener
     */
    private LoadUtils.OnLoadingListener mLoadingListener = new LoadUtils.OnLoadingListener() {
        @Override
        public void onStart(int position) {
            index = position;
//            ToastUtils.simpleToast(getActivity(), "start-----");
//            initTimer();
        }

        @Override
        public void onLoading(int length, int progress, int position) {
            if (index >= mData.size() || index < 0) return;
            mData.get(position).setProgress(progress * 100 / length);
            mAdapter.notifyDataSetChanged();
        }

        @Override
        public void onStop(int progress, int position) {
            LogUtils.v("----stop:position=" + position);
        }

        @Override
        public void onComplete(int position) {
            mData.get(position).setProgress(100);
            mAdapter.notifyDataSetChanged();
            if (position == mData.size()) isLoading = false;
            ToastUtils.simpleToast(getActivity(), "----finish");
        }

        @Override
        public void onError(Exception e, int position) {

        }

    };


    /**
     * on item click
     */
    class ItemClick implements BasicRecyclerAdapter.OnItemClickListener {

        @Override
        public void onItemClick(int position) {
            ToastUtils.simpleToast(getActivity(), "----item=" + position);
            if (mLoadUtils.isStop(position)) {
                mLoadUtils.start(position);
                return;
            }
            mLoadUtils.stop(position);
        }
    }

    /**
     * on child click
     */
    class ChildClick implements OnChildClickListener {
        @Override
        public void onClick(View v, int position) {
            if (mLoadUtils.isStop(position)) {
                mLoadUtils.start(position);
                return;
            }
            mLoadUtils.stop(position);
        }
    }

    /**
     * progress task
     */
    class ProgressTask extends TimerTask {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(12);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
